package cn.cocho.android.mc.base;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Application;
import android.os.Process;

/**
 * 通用的BaseApplication
 *
 * @author HAIKANG SONG
 * @time 2013-5-13下午4:45:52
 */
public class BaseApplication extends Application {
    private final List<WeakReference<Activity>> activitys;

    private static BaseApplication singleton;
    private Runnable doExit;

    @Override
    public void onCreate() {
        super.onCreate();
        singleton = this;
    }

    public static BaseApplication getInstance() {
        return singleton;
    }

    public BaseApplication() {
        activitys = new ArrayList<WeakReference<Activity>>();
        doExit = new Runnable() {
            @Override
            public void run() {
                closeAllActivitys();
            }
        };
    }

    public void addActivity(Activity act) {
        activitys.add(0, new WeakReference<Activity>(act));
    }

    public void removeActivity(Activity act) {
        activitys.remove(new WeakReference<Activity>(act));
    }

    private void closeAllActivitys() {
        int count = activitys.size();
        for (int i = count - 1; i >= 0; i = i - 1) {
            WeakReference<Activity> ref = activitys.get(i);
            Activity act = ref.get();
            if (act == null) {
                activitys.remove(i);
            } else if (!act.isFinishing()) {
                act.finish();
            }
        }
    }

    public void exitApp() {
        doExit.run();
        android.os.Process.killProcess(Process.myPid());
    }

}
